package com.iteaj.iot.test.server.breaker;

import cn.hutool.core.util.RandomUtil;
import com.iteaj.iot.server.ServerProtocolHandle;
import com.iteaj.iot.taos.TaosHandle;
import com.iteaj.iot.test.IotTestProperties;
import com.iteaj.iot.test.taos.TaosBreakerDataTable;
import com.iteaj.iot.test.taos.TaosBreakerUsingStable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicLong;

@Component
public class DataAcceptHandle implements ServerProtocolHandle<DataAcceptProtocol>, TaosHandle<DataAcceptProtocol> {

    @Autowired
    private IotTestProperties properties;
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object handle(DataAcceptProtocol protocol) {

        if(properties.isTaosStart()) {
            final int i = RandomUtil.randomInt(1, 9);
            if(i % 2 == 0) { // 测试自动创建数据表
                TaosBreakerUsingStable entity = new TaosBreakerUsingStable(protocol.getEquipCode());
                entity.setI(protocol.getI());
                entity.setV(protocol.getV());
                entity.setPy(protocol.getPy());
                entity.setSn(protocol.getEquipCode());
                entity.setPower1(protocol.getPower1());
                entity.setPower2(protocol.getPower2());

                return entity;
            } else { // 测试插入数据表
                TaosBreakerDataTable dataTable = new TaosBreakerDataTable();
                dataTable.setI(protocol.getI());
                dataTable.setV(protocol.getV());
                dataTable.setPy(protocol.getPy());
                dataTable.setTs(new Date());
                dataTable.setSn(protocol.getEquipCode());
                dataTable.setPower1(protocol.getPower1());
                dataTable.setPower2(protocol.getPower2());
                return dataTable;
            }

        } else {
            return null;
        }
    }

    /**
     * 批量写入时的最大条数
     * @return
     */
    @Override
    public int maxOfPeer() {
        return 1000;
    }

    /**
     * 多长时间周期入库一次
     * @return
     */
    @Override
    public long period() {
        return 10;
    }
}
